package com.thirteenClassicsServer.service.impl;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.google.common.collect.Lists;
import com.thirteenClassics.vo.FileUploadResponse;
import com.thirteenClassicsServer.mapper.CatalogMapper;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class FileServiceImpl {

    //自己设置的目录
    private static final String fileDir = "fileStorage";
    private static final String jdbfileDir = "jdbFileStorage";
    private static final String picfileDir = "picFileStorage";
    private static final AtomicInteger SUFFIX = new AtomicInteger(0);
    //拦截的url，虚拟路径
    public String jdbPathPattern = "jdbFiles";
    public String picPathPattern = "picFiles";
    //上传文件存放目录  =  工作目录绝对路径 + 自己设置的目录，也可以直接自己指定服务器目录
    //windows本地测试
    //绝对路径: D:\develop\work\project\myblog\myblog-file-upload\fileStorage\202302021010345680.jpg
    //System.getProperty("user.dir")   D:\develop\work\project\myblog\myblog-file-upload
    //fileDir                          fileStorage
    //fileName                         202302021010345680.jpg
    public String filePath = System.getProperty("user.dir") + File.separator + fileDir + File.separator;

    public String jdbFilePath =
            System.getProperty("user.dir") + File.separator + fileDir + File.separator + jdbfileDir + File.separator;

    public String picFilePath =
            System.getProperty("user.dir") + File.separator + fileDir + File.separator + picfileDir + File.separator;
    @Autowired
    private CatalogMapper catalogMapper;
    @Value(value = "${file.upload.suffix:jpg,jpeg,png,bmp}")
    private String fileUploadSuffix;

    @Value(value = "${file.upload.suffix:xml,txt}")
    private String jdbfileUploadSuffix;

    public static String timeFormat(Long time) {
        if (Objects.isNull(time)) {
            return null;
        }
        DateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        return sdf.format(time);
    }

    public FileUploadResponse upload(MultipartFile file) {
        FileUploadResponse result = new FileUploadResponse();
        if (file.isEmpty()) {
            log.error("the file to be uploaded is empty");
            return result;
        }
        List<String> suffixList = Lists.newArrayList(fileUploadSuffix.split(","));

        List<String> jdbList = Lists.newArrayList(jdbfileUploadSuffix.split(","));

        List<String> combinedList = new ArrayList<>(suffixList); // 创建一个包含list1的副本
        combinedList.addAll(jdbList); // 将list2的所有元素添加到combinedList中

        try {
            //校验文件后缀
            String originalFilename = file.getOriginalFilename();
            String suffix = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
            String filename = originalFilename.substring(0, originalFilename.lastIndexOf("."));
            if (!combinedList.contains(suffix)) {
                log.error("unsupported file format");
                return result;
            }

            //首次需生成目录
            File folder = new File(jdbFilePath);//存放的实际目录
            if (!folder.exists()) {
                folder.mkdirs();
            }

            File folder2 = new File(picFilePath);//存放的实际目录
            if (!folder2.exists()) {
                folder2.mkdirs();
            }
            String fileName = "";
            String absolutePath = "";

            if (!suffixList.contains(suffix)) {
                fileName = timeFormat(System.currentTimeMillis()) + SUFFIX.getAndIncrement() + "." + suffix;
                absolutePath = jdbFilePath + fileName;
                log.info("absolutePath is {}", absolutePath);
                file.transferTo(new File(absolutePath));

                String separator = "/";
                String path = separator + jdbPathPattern + separator + fileName;
                result.setPath(path);
                result.setFileName(fileName);
            } else {

                fileName = timeFormat(System.currentTimeMillis()) + SUFFIX.getAndIncrement() + String.format("%1$5s",
                        filename).replace(' ', '0')
                        + "." + suffix;

                absolutePath = picFilePath + fileName;
                log.info("absolutePath is {}", absolutePath);
                file.transferTo(new File(absolutePath));

                String separator = "/";
                String path = separator + picPathPattern + separator + fileName;
                result.setPath(path);
                result.setFileName(fileName);
            }

            //            String fileName = timeFormat(System.currentTimeMillis()) + SUFFIX.getAndIncrement() + "." +
            //            suffix;
            //            String absolutePath = filePath + fileName;
            //            log.info("absolutePath is {}", absolutePath);
            //            file.transferTo(new File(absolutePath));


        } catch (Exception e) {
            log.error("the file upload error occurred. e ", e);
        }
        return result;
    }

    public String txtToString(MultipartFile file) {
        if (!file.isEmpty()) {
            try {
                // 读取上传文件的内容
                StringBuilder fileContent = new StringBuilder();
                try (BufferedReader reader = new BufferedReader(
                        new InputStreamReader(file.getInputStream(), StandardCharsets.UTF_8))) {
                    String line;
                    while ((line = reader.readLine()) != null) {
                        fileContent.append(line).append("\n");
                    }
                }

                return fileContent.toString();
            } catch (IOException e) {
                return "文件上传失败: " + e.getMessage();
            }
        } else {
            return "上传的文件为空";
        }

    }

    public FileUploadResponse uploadpic(MultipartFile file, String catalogName, String lang, Long CatalogId,
            Long BookId) {
        String combinedId = String.format("%05d_%05d", CatalogId, BookId);
        FileUploadResponse result = new FileUploadResponse();
        if (file.isEmpty()) {
            log.error("the file to be uploaded is empty");
            return result;
        }
        List<String> suffixList = Lists.newArrayList(fileUploadSuffix.split(","));

        List<String> jdbList = Lists.newArrayList(jdbfileUploadSuffix.split(","));

        List<String> combinedList = new ArrayList<>(suffixList); // 创建一个包含list1的副本
        combinedList.addAll(jdbList); // 将list2的所有元素添加到combinedList中

        try {
            //校验文件后缀
            String originalFilename = file.getOriginalFilename();
            String suffix = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
            String filename = originalFilename.substring(0, originalFilename.lastIndexOf("."));
            if (!combinedList.contains(suffix)) {
                log.error("unsupported file format");
                return result;
            }

            //首次需生成目录
            File folder = new File(jdbFilePath);//存放的实际目录
            if (!folder.exists()) {
                folder.mkdirs();
            }

            File folder2 = new File(picFilePath);//存放的实际目录
            if (!folder2.exists()) {
                folder2.mkdirs();
            }
            String fileName = "";
            String absolutePath = "";

            if (!suffixList.contains(suffix)) {
                fileName = timeFormat(System.currentTimeMillis()) + SUFFIX.getAndIncrement() + "." + suffix;
                absolutePath = jdbFilePath + fileName;
                log.info("absolutePath is {}", absolutePath);
                file.transferTo(new File(absolutePath));

                String separator = "/";
                String path = separator + jdbPathPattern + separator + fileName;
                result.setPath(path);
                result.setFileName(fileName);
            } else {

                //                fileName = lang+catalogName+SUFFIX.getAndIncrement() + String.format("%1$5s",
                //                filename).replace(' ', '0')
                //                        + "." + suffix;
                fileName = combinedId + "_" + String.format("%1$3s", filename).replace(' ', '0')
                        + "." + suffix;

                absolutePath = picFilePath + fileName;
                log.info("absolutePath is {}", absolutePath);
                file.transferTo(new File(absolutePath));

                String separator = "/";
                String path = separator + picPathPattern + separator + fileName;
                result.setPath(path);
                result.setFileName(fileName);
            }

            //            String fileName = timeFormat(System.currentTimeMillis()) + SUFFIX.getAndIncrement() + "." +
            //            suffix;
            //            String absolutePath = filePath + fileName;
            //            log.info("absolutePath is {}", absolutePath);
            //            file.transferTo(new File(absolutePath));


        } catch (Exception e) {
            log.error("the file upload error occurred. e ", e);
        }
        return result;
    }


    //    public void excelImport(MultipartFile file) throws Exception {
    //        catalogMapper.deleteCatalog();
    //
    //
    //        String originalFilename=file.getOriginalFilename();
    //        int index=originalFilename.lastIndexOf(".");
    //        String extname=originalFilename.substring(index);
    //        String newFileName= UUID.randomUUID().toString()+extname;
    //        log.info("新的文件名：{}",newFileName);
    //        file.transferTo(new File());
    //
    //
    //        Workbook workbook = null;
    //        FileOutputStream outputStream = null;
    //        FileInputStream inputStream=null;
    //
    //        //Step 1:打开
    //        try {
    //            inputStream = new FileInputStream(new File(filePath+newFileName));
    //            workbook = new XSSFWorkbook(inputStream);
    //        } catch (IOException e) {
    //            e.printStackTrace();
    //        }
    //
    //        FileInputStream excelFile = new FileInputStream(new File(filePath+newFileName));
    //
    //        Sheet sheet = workbook.getSheetAt(0); // 选择工作表，通常第一个工作表索引为0
    //
    //        // 假设第二列的索引是1（索引从0开始）
    //        int columnIndex = 1;
    //
    //        // 遍历工作表中的每一行
    //        for (Row row : sheet) {
    //            // 获取指定列的单元格
    //            Cell cell = row.getCell(columnIndex);
    //
    //            if (cell != null) {
    //                // 检查单元格类型，确保是数字或文本类型
    //                String cellValue = cell.toString();
    //                // 在这里使用单元格的值，可以根据需求进行处理
    //                System.out.println("第二列的值：" + cellValue);
    //
    //            }
    //        }
    //
    //
    //
    //
    //
    //        //catalogMapper.deleteContentIsNull();
    //    }

}
